<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { NTabs, NTabPane, NForm, NFormItem, NButton, NInput, NCheckbox, NSpace, NQrCode, NA } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { useRouter } from 'vue-router';
import { setToken } from "@/assets/utils/token";
import { LOG_IN, GET_USER_INFO } from "@/service/apis/apis";
import { useUserStore } from '../../stores/user'
import { createDiscreteApi, useLoadingBar } from 'naive-ui'
import { showMsg } from '@/assets/utils/tools';
import Axios from "axios";
import { JSEncrypt } from 'jsencrypt';
const { loadingBar } = createDiscreteApi(["loadingBar"])

const userStore = useUserStore()
const router = useRouter()
const videoRef = ref()
const videAuth = ref(true)//人脸权限
const videAuth1 = ref(false)//人脸权限

const navigators = ref<any>(
  
)


const jmg = ref()

const streams = ref()

const myConstraints = ref({
  video: {
    facingMode: "user", // 优先调用前置摄像头
  },
})


const formRef = ref<FormInst | null>(null)
const form = ref({
  user: {
    account: '',
    password: ''
  },
})

const rules = ref({
  user: {
    account: {
      required: true,
      message: '请输入姓名',
      trigger: 'blur'
    },
    password: {
      required: true,
      message: '请输入年龄',
      trigger: ['input', 'blur']
    }
  }

})

const secret = ref('')
onMounted(()=>{
  Axios.get('https://localhost:4433/token',)
    .then(function (response) {
      // console.log('AxiosAxiosAxios',response);
      secret.value = response.data.secret
      jmg.value = response.data.token
    })
    .catch(function (error) {
      console.log(error);
  });
  console.log(navigators.value );

  //监听人脸开启
  if (navigator.mediaDevices) {
    videAuth.value = true
  } else {
    videAuth.value = false
  }
})

const encrypt = (text: string) => {
    const encryptor = new JSEncrypt();
    const publicKey = secret.value
    // const publicKey = `-----BEGIN PUBLIC KEY----- ${jmg.value} -----END PUBLIC KEY-----`
    // const publicKey = '-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB -----END PUBLIC KEY-----'
    // console.log('publicKey',publicKey)
    encryptor.setPublicKey(publicKey);
    return encryptor.encrypt(form.value.user.password);
}


//标签选择 ------- 前
function handleBeforeLeave(value: string) {
  if (value == 'renlian') {
    if (navigator.mediaDevices) {
      videoOpen()
      return true
    } else {
      videoClose()
      showMsg('error', '您的浏览器不支持该功能，请检查摄像头更换浏览器或升级至最新版本')
      return false
    }

  } else {
    videoClose()
    return true
  }
}
//标签选择 --- 后---回调
function handleUpdateValue(value: string) {
  if (value == 'renlian') {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    
      videAuth1.value = false
      navigator.mediaDevices.getUserMedia(myConstraints.value).then(
        (stream) => {
          // streams.value = stream
          // videoRef.value.srcObject = stream;
          // //播放视频
          // videoRef.value.play();
          // 关闭摄像

        },
        (error) => {
          videAuth1.value = true
          console.error(error.name || error);
        }
      );

    } else {
      console.log(2222222222);

      showMsg('error', '您的浏览器不支持该功能，请检查摄像头更换浏览器或升级至最新版本')
   
    }

  }
}
/**
 * 登录
 */
function onLogIn(e: MouseEvent) {

  // let p = {
  //   username: "张三123",
  //   password: "zxc"
  // }
  let p = {
    username: form.value.user.account,
    // password: form.value.user.password,
    encryptedPassword: encrypt(form.value.user.password),
    jmg:jmg.value
  }
  
  // e.preventDefault()
  // formRef.value?.validate((errors) => {
  //   console.log(errors)
  //   if (!errors) {

  //   }
  //   else {
  //     console.log(errors)

  //   }
  // })

 

  loadingBar.start()
  // // debugger
  LOG_IN({params: JSON.stringify(p) }).then((res: any) => {
    console.log(res);
    let reult = res.data
    setToken(reult.token);
    userStore.getUserInfo()
    router.replace("/workTower");
    loadingBar.finish()
  }).catch((err) => {
    loadingBar.finish()
    showMsg('error', err.message)
  });
}


//test登录
function navto() {
  loadingBar.start()
  setToken('0001');
  router.push({ path: '/workTower' });
  loadingBar.finish()
}

// 开启摄像
function videoOpen() {
  navigator.mediaDevices.getUserMedia(myConstraints.value).then(
    (stream) => {
      streams.value = stream
      videoRef.value.srcObject = stream;
      //播放视频
      videoRef.value.play();
      // 关闭摄像

    },
    (error) => {
      console.error(error.name || error);
    }
  );
};
// 关闭摄像
function videoClose() {
  if (streams.value) {
    streams.value.getTracks().forEach((track:any) => track.stop());
  }
};


</script>
<template>
  <div class="content">
    <div class="login_box">
      <div style="font-size: xx-large;text-align: center;font-weight: 600;">
        欢迎登录
      </div>
      <n-tabs default-value="weixin" justify-content="space-evenly" type="line" style="padding: 0 30px;" trigger="click"
        @update:value="handleUpdateValue" @before-leave="handleBeforeLeave">
        <n-tab-pane name="weixin" tab="微信登录">
          <div style="text-align: center;margin-top:20px">
            <img src="../../assets/image/erweima.png" alt="" srcset="" style="width: 200px;height:200px">
            <!-- <div>
              登录即同意用户协议及内容管理规范
            </div> -->
          </div>
        </n-tab-pane>
        <!-- <n-tab-pane name="renlian" tab="人脸登录" v-if="videAuth">
          <div class="rl_box" > -->
            <!-- 人脸登录 -->
            <!-- <div class="rl_video">
              <div class="rl_video_ladding" v-if="!videAuth1">
                <video ref="videoRef" class="rl_video_ladding_video" width="250px" height="250px"></video>
              </div>
              <div class="" v-else style="text-align: center;">
               请检查设备!!!
               </div>
            </div> -->
            <!-- <canvas ref="canvasRef"  width="400px" height="400px"></canvas> -->
            <!-- canvas展示拍的照片 -->
            <!-- <canvas ref="canvasRef" style="display: none"></canvas> border: solid 1px brown;-->
            <!-- <n-button type="primary" attr-type="button" @click="">
                    拍照
              </n-button> -->
          <!-- </div>
        </n-tab-pane> -->
        <n-tab-pane name="zhanghao" tab="账号登录">
          <div style="margin-top:20px">
            <n-form ref="formRef" label-placement="left" label-width="80" :model="form" :rules="rules">
              <n-form-item label="用户名" path="user.account">
                <n-input v-model:value="form.user.account" placeholder="输入用户名" maxlength="11"/>
              </n-form-item>
              <n-form-item label="密码" path="user.password">
                <n-input type="password" v-model:value="form.user.password" placeholder="输入密码" maxlength="10"/>
              </n-form-item>
              <n-form-item>
                <div style="width: 100%;padding: 0 80px;display: flex;justify-content: space-between;">
                  <n-checkbox>
                    记住我
                  </n-checkbox>
                  <!-- <n-a>忘记密码?</n-a> -->
                </div>
              </n-form-item>
              <n-form-item>
                <div style="width: 100%;padding: 0 80px;display: flex;justify-content: center;">
                  <n-button type="primary" attr-type="button" @click="onLogIn">
                    登录
                  </n-button>
                  <!-- <n-button attr-type="button">
                    注册
                  </n-button> -->
                </div>
              </n-form-item>
            </n-form>
          </div>
        </n-tab-pane>
      </n-tabs>
      <!-- <n-button type="primary" @click="navto">test登录</n-button> -->
    </div>
  </div>
</template>
<style src="./index.scss" scoped></style>
